package com.qunar.train.mock.apache;

import com.qunar.train.mock.util.AegisLog;

import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;

import java.lang.reflect.Constructor;

/**
 * Author:zhangqianqian.zhang Date:2018/9/6
 */
public class InstanceCreatorUtil {


    public static <E> Response newResponseInstance(E t) {
        try {
            Class c = Class.forName("org.apache.http.client.fluent.Response");
            Constructor cons = c.getDeclaredConstructor(new Class[]{HttpResponse.class});
            cons.setAccessible(true);
            Response response = (Response) cons.newInstance(new Object[]{t});
            return response;
        } catch (Exception e) {
            AegisLog.log(e);
        }
        return null;
    }

    public static Content newContentInstance(byte[] raw, ContentType type) {
        try {
            Class c = Class.forName("org.apache.http.client.fluent.Content");
            Constructor cons = c.getDeclaredConstructor(new Class[]{byte[].class, ContentType.class});
            cons.setAccessible(true);
            Content content = (Content) cons.newInstance(raw, type);
            return content;
        } catch (Exception e) {
            AegisLog.log(e);
        }
        return null;
    }

    //combine Response & Content
    public static Content newInstanceReturnContent(byte[] raw, ContentType type) {
        HttpResponse response = null;
        Response res = InstanceCreatorUtil.newResponseInstance(response);
        MockExecutor.setExecuteReturnValue(res);
        Content content = newContentInstance(raw, type);
        return content;
    }

    public void clear() {
    }
}

